//
//  MainViewController.swift
//  glzbowei
//
//  Created by 高伦展 on 2017/11/17.
//  Copyright © 2017年 glz. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    // MARK: - 监听方法
    ///点击撰写按钮
    ///如果‘单纯’使用‘private’运行循环将无法正确发送消息，导致奔溃
    ///如果使用 @objc 修饰符号，可以保证运行循环发生此消息，即使函数被标记为private
    @objc private func composedButtonClick(){
        //print("click me")
        
        var vc : UIViewController
        if UserAccountViewModel.sharedUserAccount.userLogin{
            vc = ComposeViewController()
        }else{
            vc = OAuthViewController()
        }
        
        let nav = UINavigationController(rootViewController: vc)
        
        present(nav, animated: true, completion: nil)
    }
    
    // MARK: - 生命周期
    override func viewDidLoad() {
        super.viewDidLoad()

        //添加控制器，并不会创建tabbar中的按钮
        //懒加载无处不在，所有控件都延迟创建的
        addChildViewControllers()
        
        //print(tabBar.subviews)
        
        addcomposedButton()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        tabBar.bringSubview(toFront: composedButton)
        
        //print(tabBar.subviews)
    }

    // MARK: - 懒加载控件
    private lazy var composedButton:UIButton = UIButton(
        imgName: "tabbar_compose_icon_add",
        bgImgName: "tabbar_compose_button")
  
}

// MARK: - 设置界面
extension MainViewController{
    
    private func addcomposedButton(){
        
        //添加按钮
        tabBar.addSubview(composedButton)
        
        //调整按钮
        let count = childViewControllers.count
        let w = view.bounds.width / CGFloat(count) - 1
        
        composedButton.frame = CGRect(x: tabBar.bounds.minX, y: tabBar.bounds.minY, width: tabBar.bounds.width, height: tabBar.bounds.height).insetBy(dx: w * 2, dy: 0)
        
        composedButton.addTarget(self, action: #selector(MainViewController.composedButtonClick), for: .touchUpInside)
    }
    
    private func addChildViewControllers(){
        
        //tabBar.tintColor = UIColor.orange;
        
        addChildViewController(vc:HomeTableViewController(),title: "首页",img: "tabbar_home")
        addChildViewController(vc:MessageTableViewController(),title: "信息",img:"tabbar_message_center")
        addChildViewController(UIViewController())
        addChildViewController(vc:DiscoverTableViewController(),title: "发现",img:"tabbar_discover")
        addChildViewController(vc:ProfileTableViewController(),title: "我",img:"tabbar_profile")
    }
    //添加控制器
    
    private func addChildViewController(vc:UIViewController,title:String,img:String){
     
        //设置标题
        vc.title = title
    
        //设置图像
        vc.tabBarItem.image = UIImage(named: img)
        
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
    
    }
}


